<?php

namespace randy\tools\units;

class SM2
{
    public function calculateInterval(int $count, float $efactor)
    {
        if ($count === 1) {
            return 1;
        }
        if ($count === 2) {
            return 6;
        }
        return round(pow($efactor, $count - 2) * 6); //否则  系数的 次数 次方 * 6
    }

    public static function calculateEFactor($efactor, $quality)
    {
        $nextEFactor = $efactor + (0.1 - (5 - $quality) * (0.08 + (5 - $quality) * 0.02));
        if ($nextEFactor > 2.5) {
            return 2.5;
        } else {
            if ($nextEFactor < 1.3) {
                return 1.3;
            } else {
                return round($nextEFactor * 10) / 10;
            }
        }
    }

    public function sm2($item)
    {
        $count = $item['count'] ?? 0;
        $efactor = $item['efactor'] ?? 2.5;
        $quality = $item['quality'];
        $nextItem = $item;

        $needRepeat = $quality < 4;
        $nextItem['efactor'] = self::calculateEFactor($efactor, $quality);
        //计算下一次的系数

        if ($quality < 3) {
            // 没有记住 则需要直接复习 直接重新开始
            $nextItem['interval'] = 0;
            $nextItem['count'] = 0;
        } else {
            $nextItem['count'] = $count + 1; //复习次数 + 1;
            $nextItem['interval'] = self::calculateInterval($nextItem['count'], $efactor);
        }
        return [
            'item'       => $nextItem,
            'needRepeat' => $needRepeat
        ];
    }
}